//
//  TrickTender.m
//  HappyStore
//
//  Created by 李小辉 on 16/7/7.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "TrickTender.h"
#import "SearchProjectCell.h"
#import "TrickTenderShaiXuan.h"
#import "TrickTenderInfo.h"
#import "SupplyChainVC.h"
@interface TrickTender ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) NSMutableArray *aryInfo; //数据源
@property (strong, nonatomic) NSMutableDictionary *muDicParameters;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) UITableView *tableView;
@property (assign, nonatomic) NSInteger type;//采购／供应
@end
static NSString *searchProjectcell = @"SearchProjectCell";
@implementation TrickTender


- (NSMutableDictionary *)muDicParameters{
    if (!_muDicParameters) {
        _muDicParameters = [NSMutableDictionary dictionary];
    }
    return _muDicParameters;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16.f],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];

    self.muDicParameters[@"page"] = @(self.page);
    [self startNetWork];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];


    if ([self.supplyChainStr isEqualToString:@"供应链"]) {
        //segmentedControl
        self.type = 2;
        NSArray *segmentedAry = @[@"采购",@"供应"];
        UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentedAry];
        segmentedControl.frame = CGRectMake(0, 0, 120, 25);
        UIFont *font = [UIFont systemFontOfSize:14];
        NSDictionary *dic = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
        [segmentedControl setTitleTextAttributes:dic forState:UIControlStateNormal];
        segmentedControl.selectedSegmentIndex = 0;
        segmentedControl.tintColor =  RGB(44, 123, 235);
        [segmentedControl addTarget:self action:@selector(indexDidChangeForSegmentedControl:) forControlEvents:UIControlEventValueChanged];
        self.navigationItem.titleView = segmentedControl;
        
    }else{
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.font = [UIFont systemFontOfSize:19];
        titleLabel.text = @"招标";
        titleLabel.textColor = RGB(45, 45, 45);
        titleLabel.textAlignment = NSTextAlignmentCenter;
        self.navigationItem.titleView = titleLabel;
        
    }
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightItem)];
    rightItem.tintColor = RGB(45, 45, 45);
    self.navigationItem.rightBarButtonItem = rightItem;

//searchBar
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, screenW, 44)];
    self.searchBar.searchBarStyle = UISearchBarStyleProminent;
    self.searchBar.placeholder = @"搜索";
    self.searchBar.barTintColor = RGB(235, 235, 235);
    self.searchBar.layer.borderWidth = 1.f;
    self.searchBar.layer.borderColor = RGB(235, 235, 235).CGColor;
    self.searchBar.delegate = self;
    [self.view addSubview:self.searchBar];
    //tableView
    
    self.page = 1;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 108, screenW, screenH - 108)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    //取消显示后退键文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 集成下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (self.aryInfo.count != 0) {
            if ([[USER_DEFAULTS objectForKey:@"isOpenSound"] boolValue]) {//声音开关
                NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                                ofType:@"wav"];
                
                SystemSoundID soundID;
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
                
                AudioServicesPlaySystemSound(soundID); //仅播放音频
            }
            self.page = 1;
            self.muDicParameters[@"page"] = @(1);
            [self startNetWork];
        }else
            [self.tableView.mj_header endRefreshing];
    }];
    
    // 集成上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page += 1;
        self.muDicParameters[@"page"] = @(self.page);
        [self startNetWork];
    }];
    self.tableView.mj_footer.hidden = YES;
    UINib *nib = [UINib nibWithNibName:@"SearchProjectCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:searchProjectcell];
    //监听筛选
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(StartShaiXuanSearch:) name:@"TrickTenderShaiXuan" object:nil];
    //去掉自定义cell底部的黑线
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
}


- (void)StartShaiXuanSearch:(NSNotification *)dic{
    self.muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];
    [self startNetWork];
}

#pragma mark - dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:self.aryInfo.count];
    return self.aryInfo.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:searchProjectcell];
    cell.TitleLabel.text = self.aryInfo[indexPath.row][@"title"];
    
    cell.AddressLabel.text = self.aryInfo[indexPath.row][@"address"];
    if ([self.supplyChainStr isEqualToString:@"供应链"]) {
        cell.IndustryLabel.text = self.aryInfo[indexPath.row][@"industry"];
        cell.PriceLabel.text = [CustomExcetion comperNumber:self.aryInfo[indexPath.row][@"money"]];
    }else{//招投标
        cell.IndustryLabel.text = self.aryInfo[indexPath.row][@"projectType"];
        cell.PriceLabel.textColor = RGB(111, 113, 121);
        //时间换算
        NSDate *date = [CustomExcetion dateFromString:self.aryInfo[indexPath.row][@"createtime"]];
        [cell.investmentLabel setTextColor:RGB(111, 113, 121)];
        cell.PriceLabel.text = [CustomExcetion prettyDateWithReference:date];
    }

    
    if ([_aryInfo[indexPath.row][@"type"] isEqualToString:@"政府"]) {
        
        cell.ProjectIconImageView.image = [UIImage imageNamed:@"政府"];
    }else if ([_aryInfo[indexPath.row][@"type"] isEqualToString:@"企业"]){
        
        cell.ProjectIconImageView.image = [UIImage imageNamed:@"企业"];
    }else{
        
        cell.ProjectIconImageView.image = [UIImage imageNamed:@"个人"];
    }

    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 103;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([self.supplyChainStr isEqualToString:@"供应链"]) {
        SupplyChainVC *supplyChainVc = [[SupplyChainVC alloc] init];
        supplyChainVc.typeId = self.type;
        supplyChainVc.resId = self.aryInfo[indexPath.row][@"id"];
        [self.navigationController pushViewController:supplyChainVc animated:YES];
    }else{
        TrickTenderInfo *trickInfoVC = [[TrickTenderInfo alloc] init];
        trickInfoVC.type = self.type;
        trickInfoVC.userId = self.userId;
        trickInfoVC.bidId = self.aryInfo[indexPath.row][@"BidId"];
        [self.navigationController pushViewController:trickInfoVC animated:YES];
    }
}
//返回
- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
//筛选
- (void)clickRightItem{
    
    TrickTenderShaiXuan *ShaiXuan = [[TrickTenderShaiXuan alloc] init];
    ShaiXuan.supplyChainStr = self.supplyChainStr;
    [self.navigationController pushViewController:ShaiXuan animated:YES];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    if (self.aryInfo.count != 0) {
        self.aryInfo = nil;
        [self.tableView reloadData];
    }
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    if (searchBar.text.length == 0) {
        return YES;
    }else{
        self.page = 1;
        self.muDicParameters[@"page"] = @(self.page);
        self.muDicParameters[@"title"] = searchBar.text;
        [self startNetWork];
        return YES;
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if (searchBar.text.length != 0) {
        [searchBar resignFirstResponder];
        self.page = 1;
        self.muDicParameters[@"page"] = @(self.page);
        self.muDicParameters[@"title"] = searchBar.text;
        [self startNetWork];
    }
}
#pragma mark - segument
-(void)indexDidChangeForSegmentedControl:(UISegmentedControl *)control{
    if (control.selectedSegmentIndex == 0) {
        self.type = 2;
        [self startNetWork];
    }else{
        self.type = 1;
        [self startNetWork];
    }
}
#pragma mark - 网络请求
- (void)startNetWork{
    //http://192.168.1.188:8080/lensum/getBidProject_app_bid.im?page=1&type=1&title=名称&projectType=项目类型&startMoney=开始金额&endMoney=结束金额&address=地区    type：1-招标 2-中标
    
    //self.muDicParameters[@"type"] = @(self.type);
    
    NSString *strURL = @"";
    if ([self.supplyChainStr isEqualToString:@"供应链"]) {
        //供应链
        strURL = @"getSupplyList_app_chain.im";
        self.muDicParameters[@"type"] = @(self.type);
    }else{
        //招投标
        strURL = @"getBidProject_app_bid.im";
        self.muDicParameters[@"type"] = @(1);
    }
    [LSHttpTool sendHttpData:strURL params:self.muDicParameters success:^(id responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        if ([dicInfo[@"result"] integerValue] ==1) {
            
            if (self.page == 1) {
                [self.tableView.mj_header endRefreshing];
                if ([self.supplyChainStr isEqualToString:@"供应链"]) {
                    self.aryInfo = [NSMutableArray arrayWithArray:dicInfo[@"data"][@"record"]] ;
                }else{//招投标
                    self.aryInfo = [NSMutableArray arrayWithArray:dicInfo[@"data"]] ;
                }
                if (self.aryInfo.count == 10 ) {
                    self.tableView.mj_footer.hidden = NO;
                }else{
                    self.tableView.mj_footer.hidden = YES;
                }
            }else{
                [self.tableView.mj_footer endRefreshing];
                NSArray *aryIn = [[NSArray alloc] init];
                if ([self.supplyChainStr isEqualToString:@"供应链"]) {
                    aryIn = dicInfo[@"data"][@"record"];
                }else{//招投标
                    aryIn = dicInfo[@"data"];
                }
                
                for (int i = 0; i < aryIn.count; i++) {
                    NSDictionary *dic = aryIn[i];
                    [self.aryInfo addObject:dic];
                }
                if (aryIn.count == 10) {
                    self.tableView.mj_footer.hidden = NO;
                }else{
                    self.tableView.mj_footer.hidden = YES;
                }
            }
            
            [self.tableView reloadData];
            [self hideBubble];
        }else{

//            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];



            [self showErrorWithTitle:[dicInfo objectForKey:@"msg"] autoCloseTime:2];

//            [MRProgressOverlayView showErrorWithStatus:[dicInfo objectForKey:@"msg"]];



            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

       [self showSingleIconBubble:error.localizedDescription];

    }];
}

@end
